package com.ruoyi.celoan.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.celoan.entity.DalianDataReportKeyEntity;
import com.ruoyi.celoan.entity.ExTradeEffectEnterprisesDetailEntity;
import com.ruoyi.celoan.entity.ExTradeEffectEnterprisesDetailSqsEntity;
import com.ruoyi.celoan.entity.ExtradeEEffectLoanInfo;
import com.ruoyi.celoan.handanUtils.HanDanHttpUtils;
import com.ruoyi.celoan.handanUtils.HanDanHttpUtilsNew;
import com.ruoyi.celoan.handanUtils.response.CountryPlatformResponse;
import com.ruoyi.celoan.mapper.ExTradeEffectEnterprisesDetailMapper;
import com.ruoyi.celoan.service.ExTradeEffectEnterprisesDetailService;
import com.ruoyi.celoan.service.IEcDalianDataReportLogsService;
import com.ruoyi.celoan.service.statistics.ExTradeEffectEnterprisesDetailSqsService;
import com.ruoyi.celoan.util.DataReportUtil;
import com.ruoyi.celoan.util.ListUtils;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.FreeImagesToPdf;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseFile;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseInformation;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseLegal;
import com.ruoyi.manage.enterprise.domain.LoginLogReport;
import com.ruoyi.manage.enterprise.service.IEcEnterpriseFileService;
import com.ruoyi.manage.enterprise.service.IEcEnterpriseInformationService;
import com.ruoyi.manage.enterprise.service.IEcEnterpriseLegalService;
import com.ruoyi.manage.enterprise.service.ILoginLogReportService;
import com.ruoyi.manage.report.domain.EnterpriseLoanInfo;
import com.ruoyi.manage.report.service.IEnterpriseLoanInfoService;
import com.xmsme.base.sdk.BaseApiClient;
import com.xmsme.base.sdk.response.StatisticsPostResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExTradeEffectEnterprisesDetailServiceImpl extends ServiceImpl<ExTradeEffectEnterprisesDetailMapper, ExTradeEffectEnterprisesDetailEntity> implements ExTradeEffectEnterprisesDetailService {
    private static final Logger log = LoggerFactory.getLogger(ExTradeEffectEnterprisesDetailServiceImpl.class);
    @Autowired
    private IEcDalianDataReportLogsService dalianDataReportLogsService;

    @Autowired
    private IEcEnterpriseLegalService iEcEnterpriseLegalService;

    @Autowired
    private IEcEnterpriseInformationService informationService;

    @Autowired
    private ILoginLogReportService loginLogReportService;

    @Autowired
    private ExTradeEffectEnterprisesDetailSqsService effectEnterprisesDetailSqsService;

    @Autowired
    private IEnterpriseLoanInfoService iEnterpriseLoanInfoService;

    @Autowired
    private IEcEnterpriseFileService iEcEnterpriseFileService;


    private String url = "/api/upload/enterprises";
//    private String url = "/api/upload/enterprisesInfo";

    public void getDataReport(String interfaceName, BaseApiClient client, DalianDataReportKeyEntity entity, String areaCode) {
        String startDate = LocalDateTime.now().plusDays(-2L).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        QueryWrapper<ExTradeEffectEnterprisesDetailEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("area_code", areaCode);
        queryWrapper.eq("isflag", Integer.valueOf(0));
        log.info("开始时间：" + startDate);
        List<ExTradeEffectEnterprisesDetailEntity> list = ((ExTradeEffectEnterprisesDetailMapper) this.baseMapper).selectList((Wrapper) queryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            List<List<ExTradeEffectEnterprisesDetailEntity>> retList = ListUtils.split(list, 1);
            this.dalianDataReportLogsService.addLogs(interfaceName + "接口上报数据开始", list.size() + "条");
            String date = LocalDate.now().toString();
            List<Long> updateList = new ArrayList<>();
            for (int i = 0; i < retList.size(); i++) {
                try {
                    List<ExTradeEffectEnterprisesDetailEntity> reportList = retList.get(i);
                    List<Long> addlist = (List<Long>) reportList.stream().map(ret -> ret.getId()).collect(Collectors.toList());
                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细日期:" + date + "上报id为：", JSONObject.toJSONString(addlist));
                    StatisticsPostResponse response = DataReportUtil.enterprises(reportList, client);
                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细返回结果:", JSONObject.toJSONString(response));
                    if (response.isSuccess()) {
                        updateList.addAll(addlist);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("数据上报异常:" + e.getMessage());
                    this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报错误:", e.getMessage());
                }
            }
            if (CollUtil.isNotEmpty(updateList)) {
                UpdateWrapper<ExTradeEffectEnterprisesDetailEntity> updateWrapper = new UpdateWrapper();
                updateWrapper.in("id", updateList);
                updateWrapper.set("isflag", Integer.valueOf(1));
                update((Wrapper) updateWrapper);
                this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报成功条数:", updateList.size() + "条");
            }
        }
    }

    @Override
    public void addEnterprisesDetail(EcEnterpriseInformation audit) {
        if (ObjUtil.isNull(audit)) {
            return;
        }

        EcEnterpriseInformation source = informationService.getById(audit.getId());
        ExTradeEffectEnterprisesDetailEntity target = new ExTradeEffectEnterprisesDetailEntity();
        EcEnterpriseLegal legal = iEcEnterpriseLegalService.lambdaQuery().eq(EcEnterpriseLegal::getEnterpriseId, source.getId()).one();
        // 映射字段（根据你的业务需求手动对应）
        target.setId(source.getId());
        target.setPlatformId(1306L);
        target.setRealNameCertification("1".equals(source.getRealNameFlag()) ? "是" : "否");
        target.setEnterpriseName(source.getEnterpriseName());
        target.setUniscId(source.getCreditCode()); // 统一社会信用代码
        target.setAddress(source.getCorrAddress());
        target.setProvince(source.getProvinceName());
        target.setCity(source.getCityName());
        target.setArea(source.getAreaName());
        target.setRegisteredCapital(source.getRegisteredCapital()); // Long -> BigDecimal
        target.setBusinessScope(source.getBusinessScope());
        target.setOperatingTimeLimitType(Long.valueOf(source.getBusinessTermType() != null ? source.getBusinessTermType() : "1"));
        target.setOperatingTimeLimitDateBegin(source.getBusinessTermStart() == null ? null : DateUtil.format(source.getBusinessTermStart(), "yyyy-MM-dd HH:mm:ss"));
        target.setOperatingTimeLimitDateEnd(source.getBusinessTermEnd() == null ? null : DateUtil.format(source.getBusinessTermEnd(), "yyyy-MM-dd HH:mm:ss"));
        target.setApprovalDate(source.getUpdateTime() == null ? null : DateUtil.format(source.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
        target.setSettlingTime(source.getCreateTime() == null ? null : DateUtil.format(source.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        target.setExternalSystemId(IdUtils.getNumberId());
        target.setIndustry(Long.valueOf(source.getIndustry() != null ? source.getIndustry() : "1"));
        target.setXwqyflag(source.getMicroFlag());

        // 其他字段根据业务逻辑填充（这里举例几个）
        target.setOperatorName(legal.getName());
        target.setOperatorIdentity("法人");
        target.setOperatorIdCardNo(legal.getIdCard());
        target.setLoaned("是"); // 默认值
        target.setAreaCode("130400");

        target.setIsPrivateEnterprise(!Arrays.asList("3", "8", "9").contains(source.getEnterpriseNature()) ? "是" : "否"); // 可根据条件判断

        boolean save = this.save(target);
    }

    @Override
    public void getHanDanDataReportNew(String interfaceName, DalianDataReportKeyEntity entity, String areaCode, String token) {
//        "/api/upload/loanEnterpriseInfo", "/api/upload/financialInstitutions",

        String[] Urls = {"/api/upload/authorizationInformation", "/api/upload/logPlatformLogin","/api/upload/loanEnterpriseInfo","/api/upload/loanEnterpriseInfo", "/api/upload/financialInstitutions"};
//        String[] Urls = {"/api/upload/loanEnterpriseInfo"};

        YearMonth currentYearMonth = YearMonth.now();
        LocalDate firstDay = currentYearMonth.atDay(1);
        LocalDate lastDay = currentYearMonth.atEndOfMonth();
        for (String srl : Urls) {

            JSONObject jsonObject = new JSONObject();
            List<JSONObject> list = new ArrayList<>();
            switch (srl) {
                case "/api/upload/enterprises":

                    List<ExTradeEffectEnterprisesDetailEntity> detailEntities = this.lambdaQuery().between(ExTradeEffectEnterprisesDetailEntity::getSettlingTime, firstDay, lastDay).list();
                    for (ExTradeEffectEnterprisesDetailEntity detailEntity : detailEntities) {

                        jsonObject.put("platformId", 1306);
                        jsonObject.put("uniscId", detailEntity.getUniscId());                     // 统一社会信用代码（杭州企业）
                        jsonObject.put("enterpriseName", detailEntity.getEnterpriseName());           // 企业名称
                        jsonObject.put("address", detailEntity.getAddress()); // 注册地址
                        jsonObject.put("realNameCertification", detailEntity.getRealNameCertification()); // 注册地址
                        jsonObject.put("operatorName", detailEntity.getOperatorName()); // 注册地址
                        jsonObject.put("operatorIdentity", "法人"); // 注册地址
                        jsonObject.put("operatorIdCardNo", detailEntity.getOperatorIdCardNo()); // 注册地址
                        jsonObject.put("industry", detailEntity.getIndustry());                                         // 假设 7 表示“软件和信息技术服务业”
                        jsonObject.put("province", detailEntity.getProvince());
                        jsonObject.put("city", detailEntity.getCity());
                        jsonObject.put("area", detailEntity.getArea());
                        jsonObject.put("registeredCapital", detailEntity.getRegisteredCapital());                            // 注册资本：500万元
                        jsonObject.put("businessScope", detailEntity.getBusinessScope()); // 经营范围
                        jsonObject.put("operatingTimeLimitType", detailEntity.getOperatingTimeLimitType());                           // 1=长期经营，0=有固定期限
                        jsonObject.put("isPrivateEnterprise", detailEntity.getIsPrivateEnterprise());                           // 1=长期经营，0=有固定期限
                        jsonObject.put("operatingTimeLimitDateBegin", detailEntity.getOperatingTimeLimitDateBegin());           // 经营期限起
                        jsonObject.put("operatingTimeLimitDateEnd", detailEntity.getOperatingTimeLimitDateEnd());             // 经营期限止（30年）
                        jsonObject.put("approvalDate", detailEntity.getApprovalDate());                          // 核准日期
                        jsonObject.put("settlingTime", detailEntity.getSettlingTime());                  // 平台入驻时间
                        jsonObject.put("externalSystemId", IdUtils.getNumberId());
                        list.add(jsonObject);
                    }
                    break;
                case "/api/upload/loanEnterpriseInfo":
                    List<EnterpriseLoanInfo> enterpriseLoanInfos = iEnterpriseLoanInfoService.getBusinessFinancingData();
                    for (EnterpriseLoanInfo loanInfo : enterpriseLoanInfos) {
                        jsonObject.put("platformId", loanInfo.getPlatformId());
                        jsonObject.put("uniscId", loanInfo.getUniscId());
                        jsonObject.put("enterpriseName", loanInfo.getEnterpriseName());
                        jsonObject.put("realNameCertification", loanInfo.getRealNameCertification());
                        jsonObject.put("operatorName", loanInfo.getOperatorName());
                        jsonObject.put("operatorIdentity", loanInfo.getOperatorIdentity());
                        jsonObject.put("operatorCardNo", loanInfo.getOperatorCardNo());
                        jsonObject.put("registeredCapital", loanInfo.getRegisteredCapital());
                        jsonObject.put("operatingTimeLimitType", loanInfo.getOperatingTimeLimitType());
                        jsonObject.put("isPrivateEnterprise", loanInfo.getIsPrivateEnterprise());
                        jsonObject.put("downLoan", loanInfo.getDownLoan());
                        jsonObject.put("loanDate", loanInfo.getLoanDate());
                        jsonObject.put("loanOrgName", loanInfo.getLoanOrgName());
                        jsonObject.put("loanOrgUniscId", loanInfo.getLoanOrgUniscId());
                        jsonObject.put("loanOrgCode", loanInfo.getLoanOrgCode());
                        jsonObject.put("loanAmount", loanInfo.getLoanAmount());         // Double 类型自动处理
                        jsonObject.put("loanRate", loanInfo.getLoanRate());
                        jsonObject.put("guaranteeMode", loanInfo.getGuaranteeMode());
                        jsonObject.put("maturity", loanInfo.getMaturity());
                        jsonObject.put("repaymentWays", loanInfo.getRepaymentWays());
                        jsonObject.put("status", loanInfo.getStatus());
                        jsonObject.put("externalSystemId", IdUtils.getNumberId());
                        list.add(jsonObject);
                    }
                    break;
                case "/api/upload/financialInstitutions":
                    // 按字段逐个赋值（使用真实感的测试数据）
                    jsonObject.put("platformId", 1);
                    jsonObject.put("name", "邯郸市尚博教育科技有限公司");            // 企业名称
                    jsonObject.put("uniscId", "91130424MA0FYXY61B");               // 统一社会信用代码
                    jsonObject.put("category", 1);                                 // 假设 1 表示“高新技术企业”
                    jsonObject.put("code", "ZZZZZZ111111111");
                    jsonObject.put("briefIntroduction", "专注于大数据分析与人工智能解决方案的国家级高新技术企业，致力于为企业数字化转型提供核心技术支持。"); // 简介
                    jsonObject.put("settlingTime", "2019-02-10 10:21:15");          // 落地时间（保持原值）
                    jsonObject.put("productCount", 15);                            // 已上线产品数量
                    jsonObject.put("higherAuthorities", "浙江省经济和信息化厅");     // 上级主管单位
                    jsonObject.put("province", "河北省");
                    jsonObject.put("city", "邯郸市");
                    jsonObject.put("area", "永年区");
                    jsonObject.put("address", "杭州市西湖区文三路555号智慧大厦A座18层"); // 详细地址
                    jsonObject.put("logo", "https://example.com/logo/91330000MA2K3JXK8H.png"); // Logo 图片 URL
                    jsonObject.put("externalSystemId", IdUtils.getNumberId());
                    list = Arrays.asList(jsonObject);
                    break;

                case "/api/upload/authorizationInformation":
                    // 创建一个空的 JSONObject
                    // 按字段逐个赋值（使用真实感的测试数据）

                    List<ExTradeEffectEnterprisesDetailSqsEntity> detailSqsEntities = effectEnterprisesDetailSqsService.lambdaQuery().between(ExTradeEffectEnterprisesDetailSqsEntity::getUpdateTime, firstDay, lastDay).list();

                    for (ExTradeEffectEnterprisesDetailSqsEntity detailSqsEntity : detailSqsEntities) {

                        jsonObject.put("platformId", 1306);
                        jsonObject.put("uniscId", detailSqsEntity.getUniscId());               // 真实格式的统一社会信用代码
                        jsonObject.put("enterpriseName", detailSqsEntity.getEnterpriseName());     // 企业名称
                        jsonObject.put("legalPersonName", detailSqsEntity.getLegalPersonName());     // 企业名称
                        jsonObject.put("legalPersonIdCardNo", detailSqsEntity.getLegalPersonIdCardNo());     // 企业法人身份证
                        jsonObject.put("authorizedInfos", detailSqsEntity.getAuthorizedInfos());     // 企业名称
                        jsonObject.put("authorizedOrgsCode", detailSqsEntity.getAuthorizedOrgsCode());     // 企业名称
                        jsonObject.put("authSource", detailSqsEntity.getAuthSource());     // 企业名称
                        jsonObject.put("count", detailSqsEntity.getCount());
                        jsonObject.put("loanStage", detailSqsEntity.getLoanStage());
                        jsonObject.put("licenseFileType", detailSqsEntity.getLicenseFileType());
                        jsonObject.put("caSupplier", detailSqsEntity.getCaSupplier());
                        jsonObject.put("validateUrl", detailSqsEntity.getValidateUrl());
                        jsonObject.put("authorizedStartTime", detailSqsEntity.getAuthorizedStartTime());
                        jsonObject.put("authorizedEndTime", detailSqsEntity.getAuthorizedEndTime());
                        jsonObject.put("externalSystemId", IdUtils.getNumberId());
                        list.add(jsonObject);

                    }
                    break;
                case "/api/upload/logPlatformLogin":

                    List<LoginLogReport> loginLogReports = loginLogReportService.lambdaQuery().between(LoginLogReport::getCreateTime, firstDay, lastDay).list();
                    for (LoginLogReport logReport : loginLogReports) {

                        // 按字段逐个赋值（补充合理测试数据）
                        jsonObject.put("platformId", 1306);           // 补充测试值
                        jsonObject.put("uniscId", logReport.getUniscId()); // 测试统一社会信用代码
                        jsonObject.put("enterpriseName", logReport.getEnterpriseName()); // 企业名称
                        jsonObject.put("loginName", logReport.getLoginName());       // 登录用户名
                        jsonObject.put("loginTime", logReport.getLoginTime()); // 登录时间
                        jsonObject.put("loginIp", logReport.getLoginIp());   // 登录 IP
                        jsonObject.put("loginPhone", logReport.getLoginPhone());   // 登录 IP
                        jsonObject.put("loginStatus", logReport.getLoginStatus());      // 登录状态：success / failed
                        jsonObject.put("externalSystemId", IdUtils.getNumberId());
                        list.add(jsonObject);

                    }
                    break;

                default:
                    break;
            }

            log.info("数据结果：", JSONObject.toJSONString(list));

            CountryPlatformResponse response = HanDanHttpUtilsNew.uploadEnterprises(srl, JSONObject.toJSONString(list), token);
            log.info(JSONObject.toJSONString(response));
        }

        return;
//        String startDate = LocalDateTime.now().plusDays(-2L).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        QueryWrapper<ExTradeEffectEnterprisesDetailEntity> queryWrapper = new QueryWrapper();
//        queryWrapper.eq("area_code", areaCode);
//        queryWrapper.eq("isflag", Integer.valueOf(0));
//        log.info("开始时间：" + startDate);
//        List<ExTradeEffectEnterprisesDetailEntity> list = ((ExTradeEffectEnterprisesDetailMapper) this.baseMapper).selectList((Wrapper) queryWrapper);
//        if (CollUtil.isNotEmpty(list)) {
//            List<List<ExTradeEffectEnterprisesDetailEntity>> retList = ListUtils.splitList(list, 40);
//            this.dalianDataReportLogsService.addLogs(interfaceName + "接口上报数据开始", list.size() + "条");
//            String date = LocalDate.now().toString();
//            List<Long> updateList = new ArrayList<>();
//            for (int i = 0; i < retList.size(); i++) {
//                try {
//                    List<ExTradeEffectEnterprisesDetailEntity> reportList = retList.get(i);
//                    List<Long> addlist = (List<Long>) reportList.stream().map(ret -> ret.getId()).collect(Collectors.toList());
//                    log.info("上报信息:" + JSONObject.toJSONString(reportList));
//                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细日期:" + date + "上报id为：", JSONObject.toJSONString(addlist));
//                    CountryPlatformResponse response = HanDanHttpUtilsNew.uploadEnterprises(this.url, JSONObject.toJSONString(reportList), token);
//                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细返回结果:", JSONObject.toJSONString(response));
//                    if (response.isApiStatus()) {
//                        updateList.addAll(addlist);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    log.info("数据上报异常:" + e.getMessage());
//                    this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报错误:", e.getMessage());
//                }
//            }
//            if (CollUtil.isNotEmpty(updateList)) {
//                UpdateWrapper<ExTradeEffectEnterprisesDetailEntity> updateWrapper = new UpdateWrapper();
//                updateWrapper.in("id", updateList);
//                updateWrapper.set("isflag", Integer.valueOf(1));
//                update((Wrapper) updateWrapper);
//                this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报成功条数:", updateList.size() + "条");
//            }
//        }
    }

    /**
     * @param id 企业id
     */
    @Override
    public void generateShouquanshu(Long id) {
        EcEnterpriseInformation enterpriseInformation = informationService.getById(id);
        List<EcEnterpriseFile> fileList = iEcEnterpriseFileService.lambdaQuery().eq(EcEnterpriseFile::getEnterpriseId, id).eq(EcEnterpriseFile::getFileType, "6").list();
        EcEnterpriseLegal enterpriseLegal = iEcEnterpriseLegalService.lambdaQuery().eq(EcEnterpriseLegal::getEnterpriseId, id).one();
        List<String> fileUrls = fileList.stream().map(m -> m.getFileUrl()).collect(Collectors.toList());
        String fileUrl = FreeImagesToPdf.generatePdfByImg(fileUrls);

        ExTradeEffectEnterprisesDetailSqsEntity enterprisesDetailSqsEntity = new ExTradeEffectEnterprisesDetailSqsEntity();
        enterprisesDetailSqsEntity.setFileUrl(fileUrl);
        enterprisesDetailSqsEntity.setEnterpriseName(enterpriseInformation.getEnterpriseName());
        enterprisesDetailSqsEntity.setUniscId(enterpriseInformation.getCreditCode());
        enterprisesDetailSqsEntity.setCount("1");
        enterprisesDetailSqsEntity.setIsflag("0");
        enterprisesDetailSqsEntity.setAuthorizedInfos("1@@2@@3@@4@@5@@6@@7@@8@@9");
        enterprisesDetailSqsEntity.setAuthorizedOrgsCode("3324523@@34563460");
        enterprisesDetailSqsEntity.setAuthSource("1");
        enterprisesDetailSqsEntity.setCount("10");
//            enterprisesDetailSqsEntity.setCaSupplier("1");
//            enterprisesDetailSqsEntity.setValidateUrl("1");
        enterprisesDetailSqsEntity.setAuthorizedStartTime(DateUtils.getDate());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        enterprisesDetailSqsEntity.setAuthorizedEndTime(LocalDateTime.now().plusMonths(4).format(formatter));
        enterprisesDetailSqsEntity.setLegalPersonName(enterpriseLegal.getName());
        enterprisesDetailSqsEntity.setLegalPersonIdCardNo(enterpriseLegal.getIdCard());
        enterprisesDetailSqsEntity.setPlatformId("1306");
        enterprisesDetailSqsEntity.setQueryUse("信息核验");
        enterprisesDetailSqsEntity.setLicenseFileType("1");
        enterprisesDetailSqsEntity.setLoanStage("3");

        effectEnterprisesDetailSqsService.save(enterprisesDetailSqsEntity);
    }

    public void getHanDanDataReport(String interfaceName, DalianDataReportKeyEntity entity, String areaCode, String token) {
        String startDate = LocalDateTime.now().plusDays(-2L).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        QueryWrapper<ExTradeEffectEnterprisesDetailEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("area_code", areaCode);
        queryWrapper.eq("isflag", Integer.valueOf(0));
        log.info("开始时间：" + startDate);

        List<ExTradeEffectEnterprisesDetailEntity> list = this.baseMapper.selectEnterpriseInfo();
        if (list.size() > 0) {
            this.saveBatch(list);
        }
        if (CollUtil.isNotEmpty(list)) {
            List<List<ExTradeEffectEnterprisesDetailEntity>> retList = ListUtils.splitList(list, 40);
            this.dalianDataReportLogsService.addLogs(interfaceName + "接口上报数据开始", list.size() + "条");
            String date = LocalDate.now().toString();
            List<Long> updateList = new ArrayList<>();
            for (int i = 0; i < retList.size(); i++) {
                try {
                    List<ExTradeEffectEnterprisesDetailEntity> reportList = retList.get(i);
                    List<Long> addlist = (List<Long>) reportList.stream().map(ret -> ret.getId()).collect(Collectors.toList());
                    log.info("上报信息:" + JSONObject.toJSONString(reportList));
                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细日期:" + date + "上报id为：", JSONObject.toJSONString(addlist));
                    CountryPlatformResponse response = HanDanHttpUtils.uploadEnterprises(this.url, JSONObject.toJSONString(reportList), token);
                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细返回结果:", JSONObject.toJSONString(response));
                    if (response.isApiStatus()) {
                        updateList.addAll(addlist);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("数据上报异常:" + e.getMessage());
                    this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报错误:", e.getMessage());
                }
            }
            if (CollUtil.isNotEmpty(updateList)) {
                UpdateWrapper<ExTradeEffectEnterprisesDetailEntity> updateWrapper = new UpdateWrapper();
                updateWrapper.in("id", updateList);
                updateWrapper.set("isflag", Integer.valueOf(1));
                update((Wrapper) updateWrapper);
                this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报成功条数:", updateList.size() + "条");
            }
        }
    }
}


/* Location:              D:\tuodayun\workspace\work\celoan-third-data-report-service-2.0.0-SNAPSHOT.jar!\BOOT-INF\classes\com\celoan\service\impl\ExTradeEffectEnterprisesDetailServiceImpl.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */
